/*
 * CreateTaskDialog.java
 *
 * Created on 19 oktober 2009, 18:02
 */

package mop.gui.task;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import mop.controller.ResourceController;
import mop.controller.TaskController;
import mop.exception.IllegalDeadlineException;
import mop.exception.IllegalDescriptionException;
import mop.exception.IllegalDuplicationException;
import mop.gui.main.MainWindow;

/**
 *
 * @author  Laurens
 */
public class CreateTaskDialog extends javax.swing.JDialog {

    /** Creates new form CreateTaskDialog */
    public CreateTaskDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        loadTasks();
        loadResources();
    }
    
    /**
     * Loads the list of tasks on which the new task can depend.
     */
    private void loadTasks()
    {
        LinkedList<String> tasks = (LinkedList<String>) TaskController.getInstance().getAllTasksList();
        
        DefaultListModel model = new DefaultListModel();
        for(String t : tasks)
            model.addElement(t);
        
        this.listDepTasks.setModel(model);
    }
    
    /**
     * Loads the list of resources which the new task can require.
     */
    private void loadResources()
    {
        LinkedList<String> resources = (LinkedList<String>) ResourceController.getInstance().getResourceList();
        
        DefaultListModel model = new DefaultListModel();
        for(String r : resources)
            model.addElement(r);
        
        this.listReqResources.setModel(model);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblCreateTask = new javax.swing.JLabel();
        lblDescription = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtDescription = new javax.swing.JTextArea();
        btnCreateTask = new javax.swing.JButton();
        btnCancel = new javax.swing.JButton();
        lblStartTime = new javax.swing.JLabel();
        txtStartTime = new javax.swing.JTextField();
        lblDeadline = new javax.swing.JLabel();
        txtDeadline = new javax.swing.JTextField();
        lblDurationWeeks = new javax.swing.JLabel();
        lblDepTasks = new javax.swing.JLabel();
        lblReqResources = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        listDepTasks = new javax.swing.JList();
        jScrollPane3 = new javax.swing.JScrollPane();
        listReqResources = new javax.swing.JList();
        txtDurationWeeks = new javax.swing.JTextField();
        lblDurationHours = new javax.swing.JLabel();
        txtDurationHours = new javax.swing.JTextField();
        txtDurationDays = new javax.swing.JTextField();
        lblDurationDays = new javax.swing.JLabel();
        lblDurationMinutes = new javax.swing.JLabel();
        txtDurationMinutes = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Create Task");

        lblCreateTask.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        lblCreateTask.setText("Create Task");
        lblCreateTask.setName("lblCreateTask"); // NOI18N

        lblDescription.setText("Description");
        lblDescription.setName("lblDescription"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        txtDescription.setColumns(20);
        txtDescription.setRows(5);
        txtDescription.setName("txtDescription"); // NOI18N
        jScrollPane1.setViewportView(txtDescription);

        btnCreateTask.setText("Create Task");
        btnCreateTask.setName("btnCreateTask"); // NOI18N
        btnCreateTask.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCreateTaskActionPerformed(evt);
            }
        });

        btnCancel.setText("Cancel");
        btnCancel.setName("btnCancel"); // NOI18N
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        lblStartTime.setText("Start Time");
        lblStartTime.setName("lblStartTime"); // NOI18N

        txtStartTime.setText("DD-MM-YYYY HH:MM");
        txtStartTime.setName("txtStartTime"); // NOI18N

        lblDeadline.setText("Deadline");
        lblDeadline.setName("lblDeadline"); // NOI18N

        txtDeadline.setText("DD-MM-YYYY HH:MM");
        txtDeadline.setName("txtDeadline"); // NOI18N

        lblDurationWeeks.setText("Duration - Weeks");
        lblDurationWeeks.setName("lblDurationWeeks"); // NOI18N

        lblDepTasks.setText("Depends on tasks...");
        lblDepTasks.setName("lblDepTasks"); // NOI18N

        lblReqResources.setText("Required Resources");
        lblReqResources.setName("lblReqResources"); // NOI18N

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        listDepTasks.setName("listDepTasks"); // NOI18N
        jScrollPane2.setViewportView(listDepTasks);

        jScrollPane3.setName("jScrollPane3"); // NOI18N

        listReqResources.setName("listReqResources"); // NOI18N
        jScrollPane3.setViewportView(listReqResources);

        txtDurationWeeks.setText("0");
        txtDurationWeeks.setName("txtDurationWeeks"); // NOI18N

        lblDurationHours.setText("Duration - Hours");
        lblDurationHours.setName("lblDurationHours"); // NOI18N

        txtDurationHours.setText("0");
        txtDurationHours.setName("txtDurationHours"); // NOI18N

        txtDurationDays.setText("0");
        txtDurationDays.setName("txtDurationDays"); // NOI18N

        lblDurationDays.setText("Duration - Days");
        lblDurationDays.setName("lblDurationDays"); // NOI18N

        lblDurationMinutes.setText("Duration - Minutes");
        lblDurationMinutes.setName("lblDurationMinutes"); // NOI18N

        txtDurationMinutes.setText("0");
        txtDurationMinutes.setName("txtDurationMinutes"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblCreateTask)
                    .addComponent(lblDepTasks)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(lblDescription)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 263, Short.MAX_VALUE)
                                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 263, Short.MAX_VALUE)
                                    .addComponent(btnCreateTask, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 263, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(6, 6, 6)))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(lblStartTime)
                                    .addComponent(lblDeadline)
                                    .addComponent(txtDeadline, javax.swing.GroupLayout.DEFAULT_SIZE, 271, Short.MAX_VALUE)
                                    .addComponent(txtStartTime))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addComponent(lblDurationWeeks)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                            .addComponent(lblDurationHours)
                                            .addComponent(txtDurationHours)
                                            .addComponent(lblReqResources)
                                            .addComponent(txtDurationWeeks, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(lblDurationMinutes)
                                            .addComponent(lblDurationDays)
                                            .addComponent(txtDurationMinutes, javax.swing.GroupLayout.DEFAULT_SIZE, 127, Short.MAX_VALUE)
                                            .addComponent(txtDurationDays, javax.swing.GroupLayout.DEFAULT_SIZE, 127, Short.MAX_VALUE)))
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                        .addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(btnCancel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 271, Short.MAX_VALUE)))
                                .addGap(10, 10, 10)))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblCreateTask)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblStartTime)
                    .addComponent(lblDescription))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(txtStartTime, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblDeadline)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtDeadline, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblDurationWeeks)
                            .addComponent(lblDurationDays))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtDurationWeeks, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtDurationDays, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblDurationHours)
                            .addComponent(lblDurationMinutes))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtDurationHours, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtDurationMinutes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblDepTasks)
                    .addComponent(lblReqResources))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 323, Short.MAX_VALUE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 323, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnCreateTask)
                    .addComponent(btnCancel))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

/**
 * Closes the dialog.
 * 
 * @param   evt
 */
private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
    this.dispose();
}//GEN-LAST:event_btnCancelActionPerformed

/**
 * Creates a task.
 * 
 * @param   evt
 */
private void btnCreateTaskActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCreateTaskActionPerformed
    String description = this.txtDescription.getText();
    
    // Parse start and end time/dates.
    SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm");
    Timestamp start = null, deadline = null;
    try {
        start = new Timestamp(((Date) formatter.parse(this.txtStartTime.getText())).getTime());
        deadline = new Timestamp(((Date) formatter.parse(this.txtDeadline.getText())).getTime());
    } catch (ParseException ex) {
        JOptionPane.showMessageDialog(null, "Wrong date(s)!", "Error", JOptionPane.ERROR_MESSAGE);
        return;
    }
    
    // Load duration.
    long ms = 0;
    ms += Long.parseLong(this.txtDurationMinutes.getText()) * 60000; // 1 minute = 60k ms
    ms += Long.parseLong(this.txtDurationHours.getText()) * 3600000; // 1 hour = 3.6m ms
    ms += Long.parseLong(this.txtDurationDays.getText()) * 86400000; // 1 day = 86.4m ms
    ms += Long.parseLong(this.txtDurationWeeks.getText()) * 604800000; // 1 week = 604.8m ms
    Timestamp duration = new Timestamp(ms);
    
    // Load dependant tasks.
    LinkedList<String> depTasks = new LinkedList<String>();
    Object[] selValues = this.listDepTasks.getSelectedValues();
    if(selValues != null)
        for(Object depTask : selValues)
            depTasks.add((String)depTask);
    
    // Load required resources.
    LinkedList<String> reqResources = new LinkedList<String>();
    selValues = this.listReqResources.getSelectedValues();
    if(selValues != null)
        for(Object reqRes : selValues)
            reqResources.add((String)reqRes);
        
    // Call controller.
    try {
        TaskController.getInstance().createTask(
                description, 
                start, 
                deadline, 
                duration, 
                depTasks, 
                reqResources);
        JOptionPane.showMessageDialog(null, "Task created!", "Success", JOptionPane.INFORMATION_MESSAGE);
        MainWindow.getInstance().update();
        this.dispose();
    } catch (IllegalDeadlineException ex) {
        JOptionPane.showMessageDialog(null, "Illegal deadline!", "Error", JOptionPane.ERROR_MESSAGE);
        return;
    } catch (IllegalDescriptionException ex) {
        JOptionPane.showMessageDialog(null, "Illegal name!", "Error", JOptionPane.ERROR_MESSAGE);
        return;
    } catch (IllegalDuplicationException ex) {
        JOptionPane.showMessageDialog(null, "Task already exists!", "Error", JOptionPane.ERROR_MESSAGE);
        return;
    }
}//GEN-LAST:event_btnCreateTaskActionPerformed                                       

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnCreateTask;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JLabel lblCreateTask;
    private javax.swing.JLabel lblDeadline;
    private javax.swing.JLabel lblDepTasks;
    private javax.swing.JLabel lblDescription;
    private javax.swing.JLabel lblDurationDays;
    private javax.swing.JLabel lblDurationHours;
    private javax.swing.JLabel lblDurationMinutes;
    private javax.swing.JLabel lblDurationWeeks;
    private javax.swing.JLabel lblReqResources;
    private javax.swing.JLabel lblStartTime;
    private javax.swing.JList listDepTasks;
    private javax.swing.JList listReqResources;
    private javax.swing.JTextField txtDeadline;
    private javax.swing.JTextArea txtDescription;
    private javax.swing.JTextField txtDurationDays;
    private javax.swing.JTextField txtDurationHours;
    private javax.swing.JTextField txtDurationMinutes;
    private javax.swing.JTextField txtDurationWeeks;
    private javax.swing.JTextField txtStartTime;
    // End of variables declaration//GEN-END:variables

}